;(function(){
    /***
     * ajax封装，设置默认使用json数据格式及标准服务返回数据，及session超时，弹出登录
     * @param options
     */
    bs.ajax = function(options){
        var deferred = when.defer();
        var setting = {
            type:'get',
            contentType:'application/json',
            dataType: 'json',
            charset:bs.charset || 'utf-8',
            context: document.body,
            success: __success,
            error: __error,
            beforeSend:function(XMLHttpRequest){
              bs.tip.loading(bs.ajax.loadingStr);
            },
            statusCode: {
                404: function () {
                    if(bs.debug){
                        bs.tip.hidden();
                        bs.tip.error('404');
                    }
                }
            }
        };
        var opts = $.extend({},setting, options);

        opts.contentType += "; charset=" + opts.charset;
        if (opts.type.toLowerCase() == "post" && bs.util.isObject(opts.data)) {
            //正在提交数据，请稍候。。。
            bs.ajax.loadingStr = "\u6B63\u5728\u63D0\u4EA4\u6570\u636E\uFF0C\u8BF7\u7A0D\u5019\u3002\u3002\u3002";
            opts.contentType = "application/x-www-form-urlencoded; charset=" + opts.charset;
        }
        if (!opts.url || opts.url == "") {
            if (bs.ajax.url != "") {
                opts.url = bs.ajax.url;
            }
        }
        return $.ajax(opts);
    };
    /**
     * get提交方式
     * @param url
     * @param datamap
     * @param okFn
     * @param failFn
     * @param errFn
     * @param options
     */
    bs.ajax.get = function(url, datamap, okFn, failFn, errFn, options){
         __getpost(url, datamap, okFn, failFn, errFn, options,'get');
    };
    /**
     * post提交方式
     * @param url
     * @param datamap
     * @param okFn
     * @param failFn
     * @param errFn
     * @param options
     */
    bs.ajax.post = function(url, datamap, okFn, failFn, errFn, options){
        __getpost(url, datamap, okFn, failFn, errFn, options, 'post');
    };
    /**
     * ajax的URL配置
     * @type {string}
     */
    bs.ajax.url = '';
    /**
     * ajax弹登录窗
     * @type {string}
     */
    bs.ajax.loginURL = '/login/mini';
    /**
     * 是否返回标准数据({status:1,data:object,desc:''})
     * @type {boolean}
     */
    bs.ajax.isNormal = true;
    /**
     * 正在加载数据，请稍候...
     * @type {string}
     */
    bs.ajax.loadingStr = '\u6B63\u5728\u52A0\u8F7D\u6570\u636E\uFF0C\u8BF7\u7A0D\u5019\u002E\u002E\u002E'
    /**
     *  错误回调处理
     * @ignore
     * @param XMLHttpRequest
     * @param textStatus
     * @param errorThrown
     * @private
     */
    function __error(XMLHttpRequest, textStatus, errorThrown, errFn, scope, deferred){
        var me = scope;
        if (bs.util.isFunction(errFn)) {
            errFn.call(me, XMLHttpRequest, textStatus, errorThrown)
        } else {
            if (bs.debug) {
                bs.tip.error(textStatus);
            } else {
                //亲，处理失败，操作取消
                bs.tip.error('\u4EB2\uFF0C\u5904\u7406\u5931\u8D25\uFF0C\u64CD\u4F5C\u53D6\u6D88\uFF01');
            }
        }
    };
    /**
     * 成功回调处理
     *
     * @ignore
     *
     * @param json
     * @param okFn
     * @param failFn
     * @param scope
     * @param deferred
     * @private
     */
    function __success(data, okFn, failFn, scope, deferred){
        var me = scope;
        if(bs.ajax.isNormal && bs.util.isObject(data)){
            deferred.resolve(data);
            if(data.status){
                if(bs.util.isFunction(okFn)){
                    okFn.call(me,data);
                }
            }else{
                __check(data.data,data.desc);
                if (bs.util.isFunction(failFn)) {
                    failFn.call(me,data);
                }

            }
        }else{
            if (bs.util.isFunction(okFn)) {
                okFn.call(me, data);
            }
        }

    };
    /***
     * 检查是否弹出重新登录
     *
     * @ignore
     *
     * @param flag
     * @private
     */
    function __check(flag,desc){
        var selfWin = window;
        if (flag == -22) { //session timeout弹出登录
            var _dg = bs.dialog.get();
            var loginDg = null;
            var _parent = null;
            if (_dg) {
                _parent = _dg;
                loginDg = _dg.get("ajaxLogin", 1);
            }
            if (loginDg == null) {
                bs.log('ajax.loginURL=' + bs.ajax.loginURL);
                bs.dialog.create({
                    id: 'ajaxLogin',
                    title: '登录',
                    self: false,
                    width: 450,
                    height: 320,
                    zIndex: 999999,
                    max: false,
                    parent: _parent,
                    resize: false,
                    close: function () {
                        var arg = this.data;
                        if (arg && arg == 1) {
                            try {
                                selfWin.location.reload();
                            } catch (e) {
                            }
                        }
                    },
                    lock: true,
                    min: false,
                    content: 'url:' + bs.ajax.loginURL
                });
            } else {
                loginDg.show();
            }
        }else if(data ==-1 && bs.util.isNull(desc)){
             bs.tip.error(desc);
        }
    };
    /**
     * get和post统一封装
     *
     * @ignore
     *
     * @param obj1 {string|object} url或data
     * @param obj2  {object|function} object或function
     * @param fn1   {*|function}
     * @param fn2   {*|function}
     * @param fn3   {*|function}
     * @param options {*|object}
     * @param type    {string} get或post
     * @returns {promise|*|G.promise|Y.promise}
     * @private
     */
    function __getpost(obj1,obj2,fn1,fn2,fn3,options,type){
         var me = this;
         var deferred = when.defer();
         var setting = {
            type:type,
            success:function(data, textStatus){
                    __success.call(me,data, fn1, fn2,me,deferred);
            },
            error:function(XMLHttpRequest, textStatus, errorThrown){
                __error.call(me, XMLHttpRequest, textStatus, errorThrown, fn3,me,deferred);
            }
         };
         var opts = $.extend({},setting,options);

         if(bs.util.isObject(obj1)){//第一个参数obj为提交参数值
             opts.data = obj1;
             if(bs.util.isFunction(obj2)){ //obj2-->okFn
                 opts.success = function(json){
                     __success.call(me,json,obj2,fn1,me, deferred);
                 }
                 if(bs.util.isFunction(fn2)){
                     opts.error = function (XMLHttpRequest, textStatus, errorThrown) {
                         __error.call(me, XMLHttpRequest, textStatus, errorThrown, fn2,me, deferred);
                     }
                 }
             }
         }else if(bs.util.isString(obj1)){
               opts.url = obj1;
               if(bs.util.isObject(obj2)){
                   opts.data = obj2;
               }else if(bs.util.isFunction(obj2)){
                   opts.success = function (json) {
                       __success.call(me, json, obj2, fn1, me, deferred);
                   }
                   if (bs.util.isFunction(fn2)) {
                       opts.error = function (XMLHttpRequest, textStatus, errorThrown) {
                           __error.call(me, XMLHttpRequest, textStatus, errorThrown, fn2, me, deferred);
                       }
                   }
               }
         }else if(bs.util.isFunction(obj1)){
             opts.success = function (json) {
                 __success.call(me, json, obj1, obj2, me, deferred);
             }
             if (bs.util.isFunction(fn1)) {
                 opts.error = function (XMLHttpRequest, textStatus, errorThrown) {
                     __error.call(me, XMLHttpRequest, textStatus, errorThrown, fn1, me, deferred);
                 }
             }
         }
         bs.ajax(opts);
         return deferred.promise;
    }
})();